package com.bckj.fastboot.core.extra.relational;

import org.springframework.util.Assert;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Update
 *
 * @author wfc
 **/
public class Update {

    private final List<String> sets = new ArrayList<>();

    private final Map<String, Object> params = new HashMap<>();

    private final String table;

    public Update(String table) {
        this.table = table;
    }

    public static Update of(String table) {
        return new Update(table);
    }

    public Update set(String field, Object value) {
        sets.add(String.format("%s = %s", field, formatValue(field, value)));
        params.put(field, value);
        return this;
    }

    private String formatValue(String field, Object value) {
        Assert.notNull(value, "value must not be null");
        return ":" + field;
    }

    public Map<String, Object> params() {
        return params;
    }

    @Override
    public String toString() {
        String str = String.join(",", sets);
        return String.format("UPDATE %s SET %s", table, str);
    }
}
